<template>
    <el-dialog v-model="isShowEdit" :close-on-click-modal="false"	:close-on-press-escape="false" title="编辑轮播图信息" center width="80%">
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="upload-Img"
            status-icon
        >
            <el-form-item label="上传图片" prop="img">
                <el-upload ref="uploadRef" action="#" :limit="1" :on-exceed="handleExceed" list-type="picture" :on-change="file=>handleImgChange(file,fileList,'add')" :on-remove="file=>handleImgChange(file,fileList,'delete')" :auto-upload="false">
                    <div class="choose-area">
                        <Icon icon="upload-image" size="100px" />
                    </div>  
                    <template #file="{ file }">
                        <vue-cropper
                            ref="cropperRef"
                            :src="fileUrl"
                            alt="Source Image"
                            :cropBoxResizable="true"
                            :initalAspectRatio="2"
                            :aspectRatio="2"
                            :options="cropperOptions"
                            class="cropper-wrapper-add"
                            >
                            </vue-cropper>
                            <el-button type="warning" @click="handleCrop">裁剪</el-button>
                                <span class="delete-btn-wrapper" @click="handleRemove">
                            <Icon icon="delete" />
                        </span>
                    </template>
                </el-upload>
                <div class="crop-preview">
                    <img :src="previewImage" alt="" />
                </div>
            </el-form-item>
            <el-form-item label="关联影视" prop="mid">
                <el-select
                    v-model="ruleForm.mid"
                    :placeholder="ruleForm.label"
                    filterable
                    clearable
                    remote
                    reserve-keyword
                    :loading="isLoading"
                    no-match-text="无匹配数据"
                    remote-show-suffix
                    :remote-method="handleRelateInput"
                    style="width: 240px"
                >
                  <el-option
                    v-for="(item,index) in filterList"
                    :key="index"
                    :label="item.label"
                    :value="item.mid"
                  />
                </el-select>
            </el-form-item>
            <el-form-item  label="海报描述" prop="brief">
                <el-input v-model="ruleForm.brief" type="textarea" autosize clearable  show-word-limit   maxlength="88" placeholder="请输入海报描述" />
            </el-form-item>
            <el-form-item>
                <el-button  type="success" @click="submit()">确认</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <div class="carousel-wrapper">
        <div class="operate-bar">
            <span>首页轮播图</span>
            <el-button type="warning" class="add-btn" @click="addItem" round><Icon icon="add" />新增</el-button>
            <span>{{carousel_num}}/8</span>
        </div>
        <div class="carousel-list">
            <el-carousel :autoplay="false" height="500px">
                <el-carousel-item class="list-item" v-for="(item,index) in carouselList" :key="index">
                    <transition name="el-fade-in-linear">
                        <div class="shade" v-show="showShade" @mouseleave="showShade=false">
                            <div class="icon-wrapper">
                                <Icon icon="edit" size="50px" @click="editItem(item.id)" />
                                <Icon icon="delete-light" size="35px" @click="deleteItem(item.id)" />
                            </div>
                        </div>
                    </transition>
                    <div class="img-wrapper" @mouseover="showShade=true" >
                        <img :src="item.img_url" alt="轮播图" />
                    </div>
                </el-carousel-item>
            </el-carousel>
        </div>
            <div>
    <h3 class="drag-title">拖动排序</h3>
    <VueDraggable v-model="carouselList" class="drag" @update="handleChange">  
      <div v-for="(item,index) in carouselList" :key="index" class="drag-item">
        <img :src="item.img_url" class="item-img" alt="海报">
      </div>  
    </VueDraggable>  
    </div>
    </div>


</template>

<script setup>
  import { ref,onBeforeMount,computed} from 'vue';
  import Icon from '@/components/Icon.vue';  
  import VueCropper from 'vue-cropperjs/VueCropper';
  import { VueDraggable } from 'vue-draggable-plus'
  import 'cropperjs/dist/cropper.css';
  import debounce from 'lodash/debounce';
  import {dataURLtoFile,unique} from '@/utils/common.js';
  import {getCarousel,updateCarousel,addCarousel,deleteCarousel,editCarousel,getFilterList} from '@/api/index.js';
  import {genFileId,ElDialog,ElMessage,ElSelect,ElInput,ElOption, ElButton,ElCarousel,ElCarouselItem,ElMessageBox,ElFormItem,ElUpload,ElForm} from 'element-plus';
  const cropperOptions = {
      dragMode: 'none', // 拖拽模式
      cropBoxMovable: true, // 裁剪框是否可移动
      movable: false, // 图片是否可移动
      zoomable: true, // 图片是否可缩放
      rotatable: true, // 图片是否可旋转
      scalable: true, // 图片是否可调整大小
      zoomOnWheel: true, // 是否在鼠标滚轮上启用缩放
    }; // Cropper.js 的选项 
    /*模板引用变量*/
  const ruleFormRef = ref(null);
  const uploadRef = ref(null);
  const cropperRef = ref(null);
  const isLoading = ref(false);
let carouselList = ref([]);
onBeforeMount(()=>{
  getCarouselList();
})
 let carousel_num = computed(()=>{
  return carouselList.value.length;
 }) 
  let showShade = ref(false);
  let isShowEdit = ref(false);
  const posterObj = ref(null);
  const ruleForm = ref({
    brief:'',
    mid:null,
    orderId:null,
    img:null,
    label:null,
    id:null
  });
  //表单处理类型
  let formType = ref('add');
  const rules = ref({
      mid:[
        { required: true, message: '请选择关联电影', trigger: 'blur' },
      ],
      brief:[
        { required: true, message: '请输入简介', trigger: 'blur' },
      ]
  })
  let fileUrl = ref('');
  let previewImage = ref('');
  const filterList = ref([]); 
    /*方法*/
/*拖拽*/
// 排序
const handleChange=(e)=>{
   //let newIndex = e.newIndex;
   let list = carouselList.value.map(({id,orderId})=>({id,orderId}));
   list.forEach((item,index)=>{
     item.orderId = index+1;
   });
   updateCarousel(list).then(res=>{
     if(res.status.code === 200){
       ElMessage.success(res.status.msg);
     }else{
       ElMessage.error(res.status.msg);
     }
   })
}

/*获取轮播图信息*/
const getCarouselList = ()=>{
  getCarousel().then(res=>{
    if(res.status.code === 200){
        let tmp = res.data;
        tmp.forEach((item)=>{
            item.mid = [item.mid];
        });
        carouselList.value = tmp;
    }else{
       ElMessage.error(res.status.msg);
    }
  })
}

//新增海报
const addItem = ()=>{
    isShowEdit.value = true;
    formType.value = 'add';
    previewImage.value = null;
    ruleForm.value.img = '';
    ruleForm.value.mid = null;
    ruleForm.value.brief = '';
    ruleForm.value.label = null;
    ruleForm.value.orderId = carouselList.value.length+1;
    filterList.value.length = 0;
}
  //编辑轮播图片
  const editItem = (id)=>{
    let tmp = {...carouselList.value.find(item=>item.id === id)};
    ruleForm.value['img']=tmp.img_url;
    ruleForm.value['id']=tmp.id;
    ruleForm.value['orderId']=tmp.orderId;
    ruleForm.value['brief']=tmp.brief;
   ruleForm.value['label']=tmp.label;
   filterList.value.push({mid:tmp.mid,label:tmp.label});
   filterList.value = unique(filterList.value,'mid');
    formType.value = 'edit';
    fileUrl.value = tmp.img_url;
    previewImage.value = tmp.img_url;
    isShowEdit.value = true;
  }
  //删除轮播图片
  const deleteItem = (id)=>{
    ElMessageBox.confirm(
        '确定删除当前轮播图吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal:false,
            closeOnPressEscape:false,	
            draggable:true,
            showClose:false,
            type: 'warning',
            center: true,
        }).then(() => {
        //向后端发起删除请求
        deleteCarousel({id}).then(res=>{
            if(res.status.code === 200){
                //删除成功后，从数组中移除该轮播图
                carouselList.value = carouselList.value.filter(item=>item.id !== id);
            }else{
                ElMessage.error(res.status.msg);
            }
        });  
        }).catch(() => {
            
        })
  }
  //替换之前上传的图片
const handleExceed = (files) => {
      uploadRef.value.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      uploadRef.value.handleStart(file);
}
//关闭预览图片
const handleRemove = () => {
    handleImgChange(null,null,'delete');
    uploadRef.value.clearFiles();
}
//处理图片的改变
const handleImgChange = (file,fileList,type)=>{
    if(type === 'add'){
        fileUrl.value = file.url;
        ruleForm.value.img = file.raw;
    }else{
        uploadRef.value.clearFiles();
        fileUrl.value = '';
        ruleForm.value.img = null;
    }
}
//确认裁剪
const handleCrop =()=>{
    if (cropperRef.value) {  
        const canvas = cropperRef.value.getCroppedCanvas();  
        // 使用 canvas.toDataURL() 获取裁剪后的图像  
        const base64Image = canvas.toDataURL();
        fileUrl.value = base64Image;
        previewImage.value = base64Image;
        posterObj.value = dataURLtoFile(base64Image, 'carousel.jpg');
        handleRemove();
      }  
}



//在线筛选查询
const relateFilter = (query)=>{
    isLoading.value = true;
    filterList.value = [];
    let keywords = query.trim();
    if(keywords){
        getFilterList({keywords},true).then(res=>{
            if(res.status.code === 200){
                filterList.value = res.data;
            }else{
                filterList.value = [];
            }
            isLoading.value = false;
        });
    }else{
        filterList.value = [];
    }
}
const debounceRelateFilter = debounce(relateFilter, 500);
const handleRelateInput = (query)=>{
    debounceRelateFilter(query);
}
//提交新增或修改
const submit = ()=>{
        let currentType = formType.value === 'add';
        if(!currentType && !ruleForm.value.mid){
            ruleForm.value.mid = [0];
        }
            ruleFormRef.value.validate((valid) => {
            if (valid) {
                if(currentType){
                    if(posterObj.value){
                        addCarousel({mid:ruleForm.value['mid'],brief:ruleForm.value.brief,orderId:ruleForm.value.orderId,img:posterObj.value}).then(res=>{
                            if(res.status.code === 200){
                                //关闭修改框
                                isShowEdit.value = false;
                                //新增
                                getCarouselList();
                            }else{
                                ElMessage.error(res.status.msg);
                            }
                        });
                    }else{
                            ElMessage.error('请先上传图片');
                    }
                }else{
                    let mid = Array.isArray(ruleForm.value['mid']) ? ruleForm.value['mid'][0] : ruleForm.value['mid'];
                    editCarousel({id:ruleForm.value.id,mid,brief:ruleForm.value.brief,img:posterObj.value}).then(res=>{
                        if(res.status.code === 200){
                                //关闭修改框
                                isShowEdit.value = false;
                                getCarouselList();
                            }else{
                                ElMessage.error(res.status.msg);
                            }
                    });
                }
            }
        });
}


</script>

<style scoped lang='scss'>
:deep(.cropper-container){
    width:630px !important;
    height:330px !important;
}
.cropper-wrapper-add{
    width:650px;
    height:275px;
}
.drag-title{
    text-align: center;
}
.drag{
    display:flex;
    justify-content: center;
}
.drag-item{
    width:200px;
    height:100px;
    border:1px solid #ccc;
    cursor: move;
    img{
        width: 100%;
        height:100%;
        object-fit: cover;
    }
}
.crop-preview{
    width:800px;
    height:400px;
    margin-top:20px;
    border:1px dotted #ccc;
    img{
        width: 100%;
        height: 100%;
        object-fit: contain;
    }
}
.carousel-wrapper{
    padding: 10px;
    height: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    .operate-bar{
        display: flex;
        align-items: center;
        margin:30px 15px;
        span{
            display: inline-block;
            font-size: 18px;
            color: #606266;
        }
        .add-btn{
            margin:0 15px;
        }
    }
    $height: 500px;
    .carousel-list{
        background-color: #d6d6d6;
        height: $height;
        position: relative;
        .list-item{
            width:100%;
            height: 100%;
            display: flex;
            justify-content: center;
            .shade{
                position:absolute;
                width:calc($height*2);
                height: 100%;
                background-color: #0000009b;
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 10;
                .icon-wrapper{
                    width:120px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }
        }
        .img-wrapper{
            position:absolute;
            width:calc($height*2);
            height: 100%;
            margin:0 auto;
            
            img{
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
        }
        
    }
}
    

</style>    